#include "xprint.h"

using namespace std;

void Print::Print(Print::printArg &p, std::map<std::string,Variable*> *v)
{//a changer aussi
	if(p.plist.front().type == Print::Text)
	{
		cout << p.plist.front().text;
		p.plist.pop();
	}
	else if(p.plist.front().type == Print::Var)
	{
		Variable *var = NULL;
		int vpos;

		for(uint i = 0; i<=v->size()-1; i++)
		{
			if(v->at(i)->getName() == p.plist.front().tvar)
			{
				var = v->at(i);
				vpos = i;
				break;
			}
		}
		
		Int *iv = static_cast<Int*>(v->at(vpos));
		Real *fv = static_cast<Real*>(v->at(vpos));

		switch(v->at(vpos)->getType())
		{
		case INT:
			cout << *(int*)iv->getValue();
			break;
		case REAL:
			cout << *(float*)fv->getValue();
			break;
		}
	}
}

Print::printArg *Print::pLex(std::string pParams)
{
	int lastsep = 0;
    int lexes = 0;
	bool found = false;
	int hml = -1;
	Print::printArg *pa = new printArg();
	std::string tokens = ",\n";

	string target = pParams;
	io()->dbgMsg("Printer lexer procedure initiated with params: ", target+ "->"+ "\""+ tokens+ "\"");

    pa->origin = io()->stripN(target);
    pa->tokens = tokens;
    target = io()->stripN(target);

    io()->dbgMsg("Last character: ", &target.at(target.size()-1));

	for(uint i = 0; i<=tokens.size()-1; i++)
	{
		if(target.find(tokens.at(i)) != FIND_ERROR_CODE)
		{
			found = true;
			break;
		}
		else
			found = false;
	}

	if(!found)
	{
		Print::pComponent pc;
		pc.text = pa->origin;
		pc.type = Print::Text;
		pa->plist.push(pc);
		return pa;
	}		

    for(uint i = 0; i<=target.size()-1; i++)
    {
        for(uint j = 0; j<=tokens.size()-1; j++)
        {
			if(i == target.size()-1)
			{
				Print::pComponent pc;

				pc.type = Print::Text;
				pc.text = target.substr(lastsep, target.size()-1);

				pa->plist.push(pc);
				lexes++;

				return pa;
			}
            if(target[i] == tokens[j])
            {
                if(lexes >= hml)
                {
					std::string lstr = pa->origin.substr(lastsep,pa->origin.size());

					Print::pComponent pc;
					pc.text = lstr;
					pc.type = Print::Text;

                    pa->plist.push(pc);
                    return pa;
                }
				else
				{
					Print::pComponent pc;
					pc.text = target.substr(lastsep, i);
					pc.type = Print::Text;

					pa->plist.push(pc);

					for(uint j = 0; j <= pa->tokens.size(); j++)
					{
						if(target[i+1] == tokens[j])
						{
							lastsep = i+2;
						}
						else
						{
							lastsep = i+1;
						}
					}

					lastsep = i+1;
					lexes++;
				}
            }
        }
    }

	if(pa->plist.size() == 0)
	{
		Print::pComponent pc;
		pc.type = Print::Text;
		pc.text = target;
        pa->plist.push(pc);
	}

    return pa;
}

void execPrint(cmd command, std::map<std::string,Variable*> *v)
{
	
}
